package com.example.jvm.study;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 自定义类加载器
 *
 * @author jl
 * @since 2021/6/6 17:02
 */
public class MyClassLoader extends ClassLoader {

    private String myName;

    public MyClassLoader(String myName) {
        this.myName = myName;
    }

    @Override
    protected Class<?> findClass(String name) {
        byte[] data = this.loadClassData(name);
        return this.defineClass(name, data, 0, data.length);
    }

    private byte[] loadClassData(String clsName) {
        byte[] data = null;
        InputStream in;
        clsName = clsName.replace(".", "/");

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            in = new FileInputStream("study/" + clsName + ".class");
            int a;
            while ((a = in.read()) != -1) {
                out.write(a);
            }
            data = out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}
